// TabBar 组件 - 标签页管理核心组件
// 支持标签页显示、切换、关闭等基础功能，包含未保存状态指示器

import React, { useCallback, useRef, useEffect, useState } from 'react';
import { X, Plus, MoreHorizontal, Circle } from 'lucide-react';
import { useTabStore, Tab, TabStatus } from '../stores/tabStore';
import { TabContextMenu } from './TabContextMenu';
import { cn } from '../utils/cn';

// 标签页组件属性
interface TabItemProps {
  tab: Tab;
  isActive: boolean;
  isDragging: boolean;
  isDropTarget: boolean;
  onActivate: (tabId: string) => void;
  onClose: (tabId: string, event: React.MouseEvent) => void;
  onContextMenu: (tabId: string, event: React.MouseEvent) => void;
  onDragStart: (tabId: string, event: React.DragEvent) => void;
  onDragEnd: (event: React.DragEvent) => void;
  onDragOver: (event: React.DragEvent) => void;
  onDrop: (event: React.DragEvent) => void;
}

// 单个标签页组件
const TabItem: React.FC<TabItemProps> = ({
  tab,
  isActive,
  isDragging,
  isDropTarget,
  onActivate,
  onClose,
  onContextMenu,
  onDragStart,
  onDragEnd,
  onDragOver,
  onDrop,
}) => {
  const [isHovered, setIsHovered] = useState(false);

  // 获取状态指示器
  const getStatusIndicator = () => {
    switch (tab.status) {
      case TabStatus.Modified:
        return (
          <div title="文件已修改">
            <Circle
              size={8}
              className="fill-orange-500 text-orange-500 flex-shrink-0"
            />
          </div>
        );
      case TabStatus.Saving:
        return (
          <div
            className="w-2 h-2 bg-blue-500 rounded-full animate-pulse flex-shrink-0"
            title="保存中..."
          />
        );
      case TabStatus.Error:
        return (
          <div title="保存失败">
            <Circle
              size={8}
              className="fill-red-500 text-red-500 flex-shrink-0"
            />
          </div>
        );
      case TabStatus.New:
        return (
          <div title="新文件">
            <Circle
              size={8}
              className="fill-green-500 text-green-500 flex-shrink-0"
            />
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div
      className={cn(
        'group relative flex items-center px-3 py-2 border-r border-gray-200 dark:border-gray-700',
        'cursor-pointer select-none transition-all duration-200',
        'hover:bg-gray-100 dark:hover:bg-gray-700',
        isActive && 'bg-white dark:bg-gray-800 border-b-2 border-blue-500',
        isDragging && 'opacity-30 scale-95 z-50 shadow-lg',
        isDropTarget && 'bg-blue-50 dark:bg-blue-900/20 border-blue-300 dark:border-blue-600',
        tab.isTemporary && 'italic text-gray-500 dark:text-gray-400',
        'min-w-0 max-w-48' // 限制标签页宽度
      )}
      draggable
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onClick={() => onActivate(tab.id)}
      onContextMenu={(e) => onContextMenu(tab.id, e)}
      onDragStart={(e) => onDragStart(tab.id, e)}
      onDragEnd={onDragEnd}
      onDragOver={onDragOver}
      onDrop={onDrop}
      title={tab.filePath}
    >
      {/* 文件名 */}
      <span className="text-sm font-medium truncate max-w-32 flex-shrink">
        {tab.fileName}
      </span>

      {/* 状态指示器 */}
      <div className="ml-2 flex-shrink-0">
        {getStatusIndicator()}
      </div>

      {/* 关闭按钮 */}
      <button
        className={cn(
          'ml-2 p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600',
          'opacity-0 group-hover:opacity-100 transition-opacity duration-200',
          'flex-shrink-0',
          isActive && 'opacity-100'
        )}
        onClick={(e) => {
          e.stopPropagation();
          onClose(tab.id, e);
        }}
        title="关闭标签页"
      >
        <X size={12} />
      </button>

      {/* 拖拽插入指示器 */}
      {isDropTarget && (
        <>
          <div className="absolute left-0 top-0 bottom-0 w-1 bg-blue-500 z-10" />
          <div className="absolute inset-0 bg-blue-50 dark:bg-blue-900/20 pointer-events-none" />
        </>
      )}
    </div>
  );
};

// TabBar 主组件属性
interface TabBarProps {
  className?: string;
  showAddButton?: boolean;
  showOverflowMenu?: boolean;
  showGroupManager?: boolean;
  maxVisibleTabs?: number;
  onNewTab?: () => void;
  onTabDragToGroup?: (tabId: string, groupId: string) => void;
}

// TabBar 主组件
export const TabBar: React.FC<TabBarProps> = ({
  className,
  showAddButton = true,
  showOverflowMenu = true,
  showGroupManager = false,
  maxVisibleTabs = 15,
  onNewTab,
  onTabDragToGroup,
}) => {
  const {
    tabs,
    tabOrder,
    activeTabId,
    draggedTabId,
    dropTargetIndex,
    activateTab,
    closeTab,
    startDrag,
    setDropTarget,
    endDrag,
    moveTab,
  } = useTabStore();

  const tabBarRef = useRef<HTMLDivElement>(null);
  const [visibleTabs, setVisibleTabs] = useState<string[]>([]);
  const [overflowTabs, setOverflowTabs] = useState<string[]>([]);
  const [showContextMenu, setShowContextMenu] = useState<{
    show: boolean;
    x: number;
    y: number;
    tabId: string;
  }>({ show: false, x: 0, y: 0, tabId: '' });

  // 计算可见标签页
  useEffect(() => {
    if (tabOrder.length <= maxVisibleTabs) {
      setVisibleTabs(tabOrder);
      setOverflowTabs([]);
    } else {
      // 确保活动标签页始终可见
      let visible = [...tabOrder];
      if (activeTabId && !visible.slice(0, maxVisibleTabs).includes(activeTabId)) {
        // 将活动标签页移到可见区域
        visible = visible.filter(id => id !== activeTabId);
        visible.splice(maxVisibleTabs - 1, 0, activeTabId);
      }
      
      setVisibleTabs(visible.slice(0, maxVisibleTabs));
      setOverflowTabs(visible.slice(maxVisibleTabs));
    }
  }, [tabOrder, activeTabId, maxVisibleTabs]);

  // 处理标签页激活
  const handleActivateTab = useCallback((tabId: string) => {
    activateTab(tabId);
  }, [activateTab]);

  // 处理标签页关闭
  const handleCloseTab = useCallback(async (tabId: string, event: React.MouseEvent) => {
    event.stopPropagation();
    
    // 如果是中键点击，直接关闭
    if (event.button === 1) {
      await closeTab(tabId);
      return;
    }

    // 检查是否有未保存的更改
    const tab = tabs.get(tabId);
    if (tab && tab.status === TabStatus.Modified) {
      // 这里应该显示确认对话框
      const confirmed = window.confirm(`文件 "${tab.fileName}" 有未保存的更改，确定要关闭吗？`);
      if (!confirmed) return;
    }

    await closeTab(tabId, true);
  }, [closeTab, tabs]);

  // 处理右键菜单
  const handleContextMenu = useCallback((tabId: string, event: React.MouseEvent) => {
    event.preventDefault();
    setShowContextMenu({
      show: true,
      x: event.clientX,
      y: event.clientY,
      tabId,
    });
  }, []);

  // 处理拖拽开始
  const handleDragStart = useCallback((tabId: string, event: React.DragEvent) => {
    startDrag(tabId);
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('text/plain', tabId);
  }, [startDrag]);

  // 处理拖拽结束
  const handleDragEnd = useCallback((event: React.DragEvent) => {
    endDrag();
  }, [endDrag]);

  // 处理拖拽悬停
  const handleDragOver = useCallback((event: React.DragEvent) => {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'move';

    // 计算拖拽目标位置
    const rect = tabBarRef.current?.getBoundingClientRect();
    if (rect && visibleTabs.length > 0) {
      const x = event.clientX - rect.left;
      const tabWidth = rect.width / visibleTabs.length;
      let targetIndex = Math.floor(x / tabWidth);

      // 确保索引在有效范围内
      targetIndex = Math.max(0, Math.min(targetIndex, visibleTabs.length - 1));

      // 如果拖拽到右半部分，插入到下一个位置
      const tabCenter = (targetIndex + 0.5) * tabWidth;
      if (x > tabCenter && targetIndex < visibleTabs.length - 1) {
        targetIndex += 1;
      }

      setDropTarget(targetIndex);
    }
  }, [visibleTabs.length, setDropTarget]);

  // 处理拖拽放置
  const handleDrop = useCallback((event: React.DragEvent) => {
    event.preventDefault();
    const draggedTabId = event.dataTransfer.getData('text/plain');
    
    if (draggedTabId && dropTargetIndex !== null) {
      moveTab(draggedTabId, dropTargetIndex);
    }
    
    endDrag();
  }, [dropTargetIndex, moveTab, endDrag]);

  // 关闭右键菜单
  useEffect(() => {
    const handleClickOutside = () => {
      setShowContextMenu({ show: false, x: 0, y: 0, tabId: '' });
    };

    if (showContextMenu.show) {
      document.addEventListener('click', handleClickOutside);
      return () => document.removeEventListener('click', handleClickOutside);
    }
  }, [showContextMenu.show]);

  return (
    <div className={cn('flex items-center bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700', className)}>
      {/* 标签页容器 */}
      <div
        ref={tabBarRef}
        className="flex flex-1 overflow-hidden"
        onDragOver={handleDragOver}
        onDrop={handleDrop}
      >
        {visibleTabs.map((tabId) => {
          const tab = tabs.get(tabId);
          if (!tab) return null;

          return (
            <TabItem
              key={tabId}
              tab={tab}
              isActive={activeTabId === tabId}
              isDragging={draggedTabId === tabId}
              isDropTarget={dropTargetIndex === visibleTabs.indexOf(tabId)}
              onActivate={handleActivateTab}
              onClose={handleCloseTab}
              onContextMenu={handleContextMenu}
              onDragStart={handleDragStart}
              onDragEnd={handleDragEnd}
              onDragOver={handleDragOver}
              onDrop={handleDrop}
            />
          );
        })}
      </div>

      {/* 溢出菜单 */}
      {showOverflowMenu && overflowTabs.length > 0 && (
        <button
          className="px-2 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 border-r border-gray-200 dark:border-gray-700"
          title={`${overflowTabs.length} 个隐藏的标签页`}
        >
          <MoreHorizontal size={16} />
        </button>
      )}

      {/* 新建标签页按钮 */}
      {showAddButton && (
        <button
          className="px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center"
          onClick={onNewTab}
          title="新建标签页"
        >
          <Plus size={16} />
        </button>
      )}

      {/* 右键菜单 */}
      {showContextMenu.show && (
        <TabContextMenu
          tabId={showContextMenu.tabId}
          x={showContextMenu.x}
          y={showContextMenu.y}
          onClose={() => setShowContextMenu({ show: false, x: 0, y: 0, tabId: '' })}
        />
      )}
    </div>
  );
};
